package com.erp.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.erp.po.Files;
import com.erp.service.FileServiceImpl;
import com.google.gson.Gson;


@WebServlet("/admin/files/FileServlet")
public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private FileServiceImpl fsi;

	public FileServlet() {
		fsi = new FileServiceImpl();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		String op = request.getParameter("op");
		
		System.out.println("信息 : "+op+" ----------FileServlet");
		
		if("upload".equals(op)) {
			// 上传文件
			upload(request,response);
			
		} else if("showFileByLoginName".equals(op)) {
			// 根据loginName显示上传文件
			showFileByLoginName(request,response);
			
		} else if("downLoadByid".equals(op)) {
			// 下载文件
			downLoadByid(request,response);
			
		} else if("delFileByid".equals(op)) {
			// 删除文件
			delFileByid(request,response);
			
		}
		
		
	}

	/**
	 * 删除文件
	 */
	protected void delFileByid(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		int id = Integer.parseInt(request.getParameter("id"));
		
		PrintWriter out = response.getWriter();
		// 根据 id 查询文件数据
		Files files = fsi.findFileById(id);

		String path = "/upload/" + files.getFileAutoName();
		// 真实路径
		String realPath = getServletContext().getRealPath(path);
		
		// 删除服务器上的文件
		File file = new File(realPath);
		boolean b = file.delete();
		if(b) {
			boolean c = fsi.removeFileById(id);
			if(c) {
				out.print("<script>alert('文件删除成功.');location.href='showAllFile.jsp'</script>");
			} else {
				out.print("<script>alert('文件删除失败.');history.back();</script>");
			}
		} else {
			out.print("<script>alert('文件删除失败.');history.back();</script>");
		}
		
	}

	/**
	 * 下载文件
	 */
	protected void downLoadByid(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		int id = Integer.parseInt(request.getParameter("id"));
		// 根据 id 查询文件数据
		Files files = fsi.findFileById(id);
		
		String path = "/upload/"+files.getFileAutoName();
		// 真实路径
		String realPath = getServletContext().getRealPath(path);
		
		String autoName = files.getFileAutoName();
		String ext = autoName.substring(autoName.lastIndexOf("."));
		
		String fileName = files.getFileName().concat(ext);
		
		// 处理乱码
		fileName = URLEncoder.encode(fileName, "utf-8");
		
		// 得到一个输入流
		FileInputStream in = new FileInputStream(realPath);
		
		response.reset();
		
		response.setHeader("Content-Disposition", "attachment;filename="+fileName);
		
		ServletOutputStream out = response.getOutputStream();
		byte[] b = new byte[1024];
		int len = 0;
		while((len = in.read(b)) > 0) {
			out.write(b, 0, len);
		}
		
		in.close();
		out.flush();
		out.close();
		System.out.println("信息 : 下载完成");
	}

	/**
	 * 根据loginName显示上传文件
	 */
	protected void showFileByLoginName(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		
		String loginName = (String) request.getSession().getAttribute("loginName");
		
		
		List<Files> list = fsi.findFileByUserName(loginName);
		
		Gson gson = new Gson();
		response.getWriter().print(gson.toJson(list));
		
	}

	/**
	 * 上传文件
	 */
	protected void upload(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {

		// 创建 DiskFileItemFactory 工厂
		DiskFileItemFactory itemFactory = new DiskFileItemFactory();
		
		// 得到解析器
		ServletFileUpload upload = new ServletFileUpload(itemFactory);
		
		// 判断传过来的数据
		// 判断是否多部件上传
		if(ServletFileUpload.isMultipartContent(request)) {
			
			// 取值
			try {
				List<FileItem> list = upload.parseRequest(request);
				
				// 写到数据库的值
				String fileName = null;
				String fileDesc = null;
				String autoName = UUID.randomUUID().toString().replaceAll("-", "");
				String userName = (String)request.getSession().getAttribute("loginName");
				
				for (FileItem item : list) {
					// 判断是否为普通字段
					if(item.isFormField()) {
						String name = item.getFieldName();
						String value = item.getString("utf-8");
						
						if("fileName".equals(name)) {
							fileName = value;
						} else if("fileDesc".equals(name)) {
							fileDesc = value;
						}
					} else {
						
						// 获取上传输入流
						InputStream in = item.getInputStream();
						
						String name = item.getName();
						System.out.println("上传文件名: "+name);
						String ext = name.substring(name.lastIndexOf("."));
						System.out.println("文件格式: "+ext);

						autoName += ext;
						// 文件上传
						String realPath = getServletContext().getRealPath("/upload");
						System.out.println("上传到服务器的路径: "+realPath);
						
						File file = new File(realPath,autoName);
						
						FileOutputStream out = new FileOutputStream(file);
						
						byte[] b = new byte[1024];
						int len = 0;
						while ((len = in.read(b)) > 0) {
							out.write(b, 0, len);
						}
						in.close();
						out.close();
					}
				}
				System.out.println("fileName="+fileName+"   fileDesc="+fileDesc+"   autoName="+autoName+"   userName="+userName);
				
				// 把数据添加到数据库
				
				int i = fsi.addFile(new Files(fileName, fileDesc, autoName, userName));
				PrintWriter out = response.getWriter();
				if(i > 0) {
					out.print("<script>alert('文件上传成功.');location.href='showAllFile.jsp'</script>");
				} else {
					out.print("<script>alert('文件上传失败.');history.back();</script>");
				}
				
				
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
			
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
